package org.xxx.test.client;


import com.alibaba.fastjson.JSONObject;
import com.ejlchina.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.xxx.common.constant.ApiConstant;

import java.util.Map;


/**
 * 接口调用客户端
 */
@Slf4j
public class ApiClient {


  public static String call(ApiInfoEnum apiInfo) {
    return call(null, apiInfo, null);
  }

  public static String call(String envUrl, ApiInfoEnum apiInfo, Object t) {
      //数据拼接，签名，返回header请求头
      Map<String, String> header = null;

      String url = envUrl == null ? ApiConstant.URL_127_SUPU + apiInfo.getUrl() : envUrl + apiInfo.getUrl();
      String res = "0000000";

      System.out.println(url);

      switch (apiInfo.getMethod()) {
	  case GET:
	      Map paramsMap = (Map) t;
	      header = SignUtil.getHeaderMap(ApiConstant.APP_KEY, ApiConstant.APP_SECRET, paramsMap);
	      res = HttpUtils.sync(url)
		      .addHeader(header)
		      .addUrlParam(paramsMap)
                .get().getBody().toString();
        break;
      case POST:
        header = SignUtil.getHeaderMap(ApiConstant.APP_KEY, ApiConstant.APP_SECRET);
        res = HttpUtils.sync(url)
            .addHeader(header)
            .setRequestJson(JSONObject.toJSONString(t))
            .post().getBody().toString();
        break;
      default:
        break;
    }
    return res;
  }
}
